package main

import (
	"log"
	"time"

	"github.com/quic-go/quic-go"
)

// startConnectionListener 为单个连接启动请求监听
func (c *QUICTunnelClient) startConnectionListener(pooledConn *ClientPooledConnection) {
	conn := pooledConn.Conn // 🔧 不解引用，保持为*quic.Conn类型
	connID := pooledConn.ConnectionID

	log.Printf("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
	log.Printf("🎧 [QUIC] 连接监听器启动")
	log.Printf("   ├─ ConnID: %s", connID[:8]+"...")
	log.Printf("   ├─ RemoteAddr: %s", conn.RemoteAddr())
	log.Printf("   └─ 等待服务端推送Stream...")
	log.Printf("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")

	defer func() {
		if r := recover(); r != nil {
			log.Printf("❌ [QUIC] 连接监听器panic: ConnID=%s, error=%v", connID[:8]+"...", r)
		}
		log.Printf("🛑 [QUIC] 连接监听器退出: ConnID=%s", connID[:8]+"...")
	}()

	for {
		select {
		case <-c.ctx.Done():
			log.Printf("⏹️ [QUIC] Context取消，停止监听: ConnID=%s", connID[:8]+"...")
			return
		default:
		}

		log.Printf("⏳ [QUIC] 等待AcceptStream: ConnID=%s", connID[:8]+"...")

		// 🔥 性能监控：记录AcceptStream耗时
		acceptStart := time.Now()
		stream, err := conn.AcceptStream(c.ctx)
		acceptDuration := time.Since(acceptStart)

		if err != nil {
			log.Printf("⚠️  [QUIC] AcceptStream失败: ConnID=%s, error=%v, type=%T, 等待时长=%.2fs",
				connID[:8]+"...", err, err, acceptDuration.Seconds())

			// 🔥🔥🔥 智能连接清理：连接断开时自动清理其他可能的僵尸连接
			log.Printf("🔌 [客户端] 检测到连接断开，触发智能清理: ConnID=%s", connID[:8]+"...")

			// 1. 先移除当前断开的连接
			c.connectionPool.RemoveConnection(connID, ProtocolHTTP)
			currentSize := c.connectionPool.GetSize(ProtocolHTTP)
			log.Printf("✅ [连接池] 已移除断开的连接: ConnID=%s, 剩余连接数=%d",
				connID[:8]+"...", currentSize)

			// 2. 如果还有其他连接，触发快速清理
			if currentSize > 0 {
				log.Printf("🧹 [自动清理] 异步清理可能的僵尸连接（当前连接数=%d）...", currentSize)
				go func() {
					// 短暂延迟，让其他可能断开的连接也能被移除
					time.Sleep(50 * time.Millisecond)

					removed := c.connectionPool.CleanupDisconnectedConnections(ProtocolHTTP)
					if removed > 0 {
						log.Printf("✅ [自动清理] 清理了%d个断开的连接，剩余%d个健康连接",
							removed, c.connectionPool.GetSize(ProtocolHTTP))
					} else {
						log.Printf("ℹ️  [自动清理] 无需清理，所有连接健康（连接数=%d）",
							c.connectionPool.GetSize(ProtocolHTTP))
					}
				}()
			}

			return
		}

		// 警告：如果AcceptStream耗时超过1秒
		if acceptDuration > 1*time.Second {
			log.Printf("⚠️  [QUIC] AcceptStream耗时较长: %.2fs, ConnID=%s",
				acceptDuration.Seconds(), connID[:8]+"...")
		}

		log.Printf("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
		log.Printf("📥 [QUIC] AcceptStream成功！")
		log.Printf("   ├─ ConnID: %s", connID[:8]+"...")
		log.Printf("   ├─ StreamID: %d", stream.StreamID())
		log.Printf("   └─ 启动处理器...")
		log.Printf("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")

		// 更新连接状态
		pooledConn.IncrementStreams()

		// 启动goroutine处理请求
		go func(s *quic.Stream, pc *ClientPooledConnection) {
			defer pc.DecrementStreams()
			handleStart := time.Now()
			c.handleIncomingRequest(s)
			handleDuration := time.Since(handleStart)

			// 记录处理时间
			if handleDuration > 1*time.Second {
				log.Printf("⚠️  [QUIC] 请求处理耗时较长: %.2fs, StreamID=%d, ConnID=%s",
					handleDuration.Seconds(), s.StreamID(), pc.ConnectionID[:8]+"...")
			}

			log.Printf("✅ [QUIC] 请求处理完成: StreamID=%d, 耗时=%.2fs, ConnID=%s",
				s.StreamID(), handleDuration.Seconds(), pc.ConnectionID[:8]+"...")
		}(stream, pooledConn)
	}
}

// DisconnectPool 断开连接池
func (c *QUICTunnelClient) DisconnectPool() {
	if c.connectionPool != nil {
		c.connectionPool.Close()
	}
}

// GetPoolStats 获取连接池统计信息
func (c *QUICTunnelClient) GetPoolStats() ClientPoolStats {
	if c.connectionPool != nil {
		return c.connectionPool.GetStats(ProtocolHTTP)
	}
	return ClientPoolStats{}
}
